<template>
  <div>
    <input type="text" v-model="kw" />
    <div class="sugs">
      <h3 @click="startSearch(sug.title)" v-for="(sug, i) in sugs" :key="i">
        {{ sug.title }}
      </h3>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { IAjaxData } from "@/types/types";
// interface ITitle {
//   title: string;
// }
export default Vue.extend({
  name: "SearchSug",
  data() {
    return {
      kw: "", // ts默认推断为string
      timer: undefined as undefined | number, // ts默认推断为null类型，注意：null类型和undefined类型的值只能是null和undefined类型。
      // sugs: [] as ITitle[],
      sugs: [] as { title: string }[],
    };
  },
  // created() {
  //   this.kw = this.$route.query.kw;
  // },
  watch: {
    kw(newVal: string): void {
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        const data: IAjaxData = await this.$request(
          `https://so.edianzu.com/sug?time=1662088399737&code=bfe5505b452bc2e680aa29e9d9c46d04&plat=2&q=${newVal}&size=10`,
          "GET"
        );
        this.sugs = data.data;
      }, 500);
    },
  },
  methods: {
    startSearch(title: string): void {
      this.$router.push(`/search?kw=${title}`);
    },
  },
  beforeDestroy() {
    console.log("SearchSug被卸载");
  },
});
</script>
<style lang="less" scoped></style>
